// app.ts
const app = getApp()  // 获取App实例
const { request } = require('./utils/request');  // 路径需根据实际结构调整
const { MD5 } = require('./utils/md5');

const upimgJs = require('./utils/upimg.js');
App({
  globalData: {
    imgBaseUrl: "cloud://cloud1-2gnuur292d2d5ed5.636c-cloud1-2gnuur292d2d5ed5-1301956627/",
    attachBaseUrl: "https://qny.lcyok.com/",
    uploadConfig: {
      url: "https://up-z2.qbox.me",
      token: ''
    },
    userInfo: null,
    statusBarHeight: "",
    navBarHeight: "",
    menuButtonInfo: "",
    session: null,
    upimgJs: upimgJs
  },

  getImgUrl(path) {
    return this.globalData.imgBaseUrl + path
  },

  navigateTo(url, type) {
    type = type ? type : 'navigateTo'
    if (!url.startsWith('/')) {
      url = `/${url}`;
    }

    // 根据类型调用不同API[1,3,6](@ref)
    const apis = {
      navigateTo: wx.navigateTo,
      redirectTo: wx.redirectTo,
      switchTab: wx.switchTab,
      reLaunch: wx.reLaunch
    };

    if (apis[type]) {
      (apis[type])({
        url,
        fail: (err) => console.error('跳转失败', err)
      })
    } else {
      console.error(`无效的跳转类型: ${type}`);
    }
  },
  dateFormatter(timestamp, full = false) {
    // 处理时间戳精度问题
    let ts = Number(timestamp);
    if (String(ts).length === 10) {  // 判断是否为秒级时间戳（10位）
      ts *= 1000;  // 转为毫秒级
    }

    // 创建 Date 对象
    const date = new Date(ts);

    // 公共部分：年月日
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    // 基础格式：YYYY-MM-DD
    let formattedDate = `${year}-${month}-${day}`;

    // 如果 full 为 true，追加时分秒
    if (full) {
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      formattedDate += ` ${hours}:${minutes}:${seconds}`;
    }

    return formattedDate;
  },
  request(params) {
    return request(params.className, params.params, params.isAuth);
  },
  axios(className, params, isAuth) {
    // console.log(params.op != 'ajaxUpLoginUserInfoSesion' && params.op != 'ajaxLoginUserInfoByPhone' && params.op != 'ajaxSendCode' && params.op != 'ajaxUserReg2' && params.op != 'ajaxComReg')
    // ajaxUpLoginUserInfoSesion 确定登录 ajaxLoginUserInfoByPhone登录   ajaxSendCode验证码 ajaxUserReg2普通注册  ajaxComReg 企业注册
    if (params.op != 'ajaxUpLoginUserInfoSesion' && params.op != 'ajaxLoginUserInfoByPhone' && params.op != 'ajaxSendCode' && params.op != 'ajaxUserReg2' && params.op != 'ajaxComReg') {
      if (this.globalData.session) {
        params = { ...params, ...this.globalData.session }
      }
    }

    return request(className, params, isAuth);
  },
  MD5(str) {
    return MD5(str);
  },
  parseJSONString(str) {
    if (str === null || str === undefined) {
      return {};
    }
    let trimmedStr = str.trim();
    if (trimmedStr === '') {
      return {};
    }
    // 替换所有换行符（包括\r\n, \r, \n）为转义的\n
    trimmedStr = trimmedStr.replace(/\r\n/g, '\\n').replace(/\r/g, '\\n').replace(/\n/g, '\\n');
    try {
      const parsed = JSON.parse(trimmedStr);
      if (parsed !== null && typeof parsed === 'object') {
        return parsed;
      } else {
        return {};
      }
    } catch (error) {
      return {};
    }
  },
  onLaunch() {

    const systemInfo = wx.getWindowInfo()
    const statusBarHeight = systemInfo.statusBarHeight
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
    const navBarHeight = (menuButtonInfo.top - statusBarHeight) * 2 + menuButtonInfo.height
    this.globalData.statusBarHeight = statusBarHeight
    this.globalData.navBarHeight = navBarHeight
    this.globalData.menuButtonInfo = menuButtonInfo
    this.globalData.navBarHeight = navBarHeight

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        console.log(res.code)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      },
    })
    try {
      const sessionStorage = wx.getStorageSync('session');
      if (sessionStorage) {
        this.globalData.session = sessionStorage;
        console.log('Session已从本地存储加载');
      }
    } catch (e) {
      console.error('本地存储读取失败:', e);
    }
  },
})